<template>
  <view class="game-container">
    <!-- 游戏开始界面 -->
    <view v-if="gameState === 'start'" class="start-screen">
      <view class="game-title">星际战机</view>
      <view class="game-subtitle">终极BOSS挑战</view>
      <button @click="startGame" class="start-button">开始战斗</button>
      <view class="instructions">
        <view class="instruction">
          <text class="icon">✋</text>
          <text>拖动飞机移动</text>
        </view>
        <view class="instruction">
          <text class="icon">🚀</text>
          <text>自动射击消灭敌人</text>
        </view>
        <view class="instruction">
          <text class="icon">💥</text>
          <text>击败5大BOSS通关</text>
        </view>
      </view>
    </view>

    <!-- 游戏主界面 -->
    <view v-else-if="gameState === 'playing'" class="game-screen">
      <!-- 状态栏 -->
      <view class="status-bar">
        <view class="status-item">
          <text>分数: {{ score }}</text>
        </view>
        <view class="status-item">
          <text>生命: {{ playerLives }}</text>
        </view>
        <view class="status-item" v-if="currentBoss">
          <text>BOSS: {{ currentBoss.health }}/{{ currentBoss.maxHealth }}</text>
        </view>
        <view class="status-item">
          <text>关卡: {{ currentLevel }}</text>
        </view>
      </view>

      <!-- 游戏区域 -->
      <view class="game-area" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">
        <!-- 玩家飞机 -->
        <view class="player" :style="{ 
                left: playerX + 'px', 
                top: playerY + 'px',
                opacity: playerInvincible ? (Math.sin(Date.now() / 100) > 0 ? 0.6 : 1) : 1
              }">
          <image src="/static/player.png" mode="widthFix" class="player-img"></image>
          <view class="thruster"></view>
        </view>

        <!-- 玩家子弹 -->
        <view v-for="(bullet, index) in playerBullets" :key="index" class="bullet player-bullet"
          :style="{ left: bullet.x + 'px', top: bullet.y + 'px' }">
        </view>

        <!-- 敌人飞机 -->
        <view v-for="(enemy, index) in enemies" :key="index" class="enemy" :class="'type' + enemy.type"
          :style="{ left: enemy.x + 'px', top: enemy.y + 'px' }">
          <image :src="'/static/enemy' + enemy.type + '.png'" mode="widthFix" class="enemy-img"></image>
          <view class="enemy-health-bar" v-if="enemy.health < enemy.maxHealth">
            <view class="enemy-health" :style="{ width: (enemy.health / enemy.maxHealth) * 100 + '%' }"></view>
          </view>
        </view>

        <!-- BOSS飞机 -->
        <view v-if="currentBoss" class="boss" :style="{ 
                left: currentBoss.x + 'px', 
                top: currentBoss.y + 'px',
                transform: `rotate(${currentBoss.rotation}deg)`
              }">
          <image :src="'/static/boss' + currentBoss.type + '.png'" mode="widthFix" class="boss-img"></image>
          <view class="boss-health-bar">
            <view class="boss-health" :style="{ width: (currentBoss.health / currentBoss.maxHealth) * 100 + '%' }">
            </view>
          </view>
        </view>

        <!-- 敌人子弹 -->
        <view v-for="(bullet, index) in enemyBullets" :key="index" class="bullet enemy-bullet"
          :style="{ left: bullet.x + 'px', top: bullet.y + 'px' }">
        </view>

        <!-- 爆炸效果 -->
        <view v-for="(explosion, index) in explosions" :key="index" class="explosion" :style="{ 
                left: explosion.x + 'px', 
                top: explosion.y + 'px',
                opacity: explosion.opacity,
                transform: `scale(${explosion.scale})`
              }">
        </view>

        <!-- 道具 -->
        <view v-for="(powerUp, index) in powerUps" :key="index" class="power-up" :class="powerUp.type"
          :style="{ left: powerUp.x + 'px', top: powerUp.y + 'px' }">
          <text>{{ powerUp.icon }}</text>
        </view>
      </view>

      <!-- 暂停按钮 -->
      <button @click="pauseGame" class="pause-btn">⏸</button>
    </view>

    <!-- 暂停界面 -->
    <view v-else-if="gameState === 'paused'" class="popup-screen">
      <view class="popup">
        <view class="popup-title">游戏暂停</view>
        <button @click="resumeGame" class="popup-btn resume">继续游戏</button>
        <button @click="restartGame" class="popup-btn restart">重新开始</button>
        <button @click="quitGame" class="popup-btn quit">退出</button>
      </view>
    </view>

    <!-- 游戏结束界面 -->
    <view v-else-if="gameState === 'gameOver'" class="popup-screen">
      <view class="popup">
        <view class="popup-title">游戏结束</view>
        <view class="final-score">最终得分: {{ score }}</view>
        <view class="final-level">已闯关卡: {{ currentLevel }}</view>
        <button @click="restartGame" class="popup-btn restart">再来一局</button>
        <button @click="quitGame" class="popup-btn quit">返回首页</button>
      </view>
    </view>

    <!-- 关卡完成界面 -->
    <view v-else-if="gameState === 'levelComplete'" class="popup-screen">
      <view class="popup">
        <view class="popup-title">关卡 {{ currentLevel }} 完成!</view>
        <view class="level-reward">奖励: {{ levelReward }} 分</view>
        <button @click="nextLevel" class="popup-btn next">挑战下一关</button>
      </view>
    </view>

    <!-- 通关界面 -->
    <view v-else-if="gameState === 'victory'" class="popup-screen">
      <view class="popup victory">
        <view class="popup-title">恭喜通关!</view>
        <view class="victory-message">你成功击败了所有BOSS!</view>
        <view class="final-score">最终得分: {{ score }}</view>
        <button @click="restartGame" class="popup-btn restart">再玩一次</button>
        <button @click="quitGame" class="popup-btn quit">返回首页</button>
      </view>
    </view>
  </view>
</template>

<script setup>
  import {
    ref,
    onMounted,
    onUnmounted,
    computed
  } from 'vue';

  // 窗口尺寸管理
  const windowWidth = ref(0);
  const windowHeight = ref(0);

  // 初始化窗口尺寸
  function updateWindowSize() {
    const systemInfo = uni.getSystemInfoSync();
    windowWidth.value = systemInfo.windowWidth;
    windowHeight.value = systemInfo.windowHeight;
  }

  // 游戏状态管理
  const gameState = ref('start'); // start, playing, paused, gameOver, levelComplete, victory
  const score = ref(0);
  const currentLevel = ref(1);
  const maxLevels = 5; // 总关卡数，对应5个BOSS
  const levelReward = ref(0);
  const gameLoop = ref(null);
  const lastTime = ref(0);

  // 玩家属性
  const playerSize = 60;
  const playerX = ref(0);
  const playerY = ref(0);
  const playerSpeed = ref(5);
  const playerLives = ref(3);
  const playerInvincible = ref(false);
  const playerInvincibleTimer = ref(0);
  const isTouching = ref(false);

  // 子弹属性
  const playerBullets = ref([]);
  const enemyBullets = ref([]);
  const bulletSize = 8;
  const bulletSpeed = 10;
  const fireRate = ref(15); // 射击间隔（帧）
  const fireTimer = ref(0);

  // 敌人属性
  const enemies = ref([]);
  const enemyTypes = [1, 2, 3]; // 3种普通敌人
  const enemySpawnTimer = ref(0);

  // BOSS属性
  const currentBoss = ref(null);
  const bossSpawned = ref(false);
  // 5种BOSS配置
  const bossConfigurations = [{
      type: 1,
      health: 30,
      speed: 2,
      score: 500,
      pattern: 'horizontal', // 左右移动
      attack: 'single' // 单发射击
    },
    {
      type: 2,
      health: 45,
      speed: 1.8,
      score: 800,
      pattern: 'zigzag', // 之字形移动
      attack: 'triple' // 三发射击
    },
    {
      type: 3,
      health: 60,
      speed: 1.5,
      score: 1200,
      pattern: 'circular', // 圆形移动
      attack: 'spread' // 扇形射击
    },
    {
      type: 4,
      health: 80,
      speed: 2.2,
      score: 1800,
      pattern: 'chase', // 追逐玩家
      attack: 'homing' // 跟踪弹
    },
    {
      type: 5,
      health: 120,
      speed: 2.0,
      score: 3000,
      pattern: 'phase', // 阶段式移动
      attack: 'mixed' // 混合攻击
    }
  ];

  // 爆炸效果
  const explosions = ref([]);

  // 道具系统
  const powerUps = ref([]);
  const powerUpTypes = [{
      type: 'health',
      icon: '❤️',
      effect: '增加生命值'
    },
    {
      type: 'speed',
      icon: '⚡',
      effect: '提升速度'
    },
    {
      type: 'fire',
      icon: '🔥',
      effect: '提升射速'
    },
    {
      type: 'shield',
      icon: '🛡️',
      effect: '暂时护盾'
    }
  ];

  // 初始化游戏
  function initGame() {
    updateWindowSize();
    score.value = 0;
    currentLevel.value = 1;
    playerLives.value = 3;
    playerSpeed.value = 5;
    fireRate.value = 15;
    resetPlayerPosition();

    // 清空数组
    playerBullets.value = [];
    enemyBullets.value = [];
    enemies.value = [];
    explosions.value = [];
    powerUps.value = [];
    currentBoss.value = null;
    bossSpawned.value = false;
  }

  // 重置玩家位置
  function resetPlayerPosition() {
    playerX.value = windowWidth.value / 2 - playerSize / 2;
    playerY.value = windowHeight.value - playerSize - 30;
  }

  // 开始游戏
  function startGame() {
    initGame();
    gameState.value = 'playing';
    startGameLoop();
  }

  // 开始游戏循环
  function startGameLoop() {
    lastTime.value = performance.now();
    if (gameLoop.value) cancelAnimationFrame(gameLoop.value);
    gameLoop.value = requestAnimationFrame(gameUpdate);
  }

  // 游戏主循环
  function gameUpdate(timestamp) {
    const deltaTime = timestamp - lastTime.value;
    lastTime.value = timestamp;

    // 更新玩家状态
    updatePlayer();

    // 处理射击
    handleShooting();

    // 生成敌人
    spawnEnemies(deltaTime);

    // 生成BOSS
    if (currentLevel.value <= maxLevels && !bossSpawned.value && enemies.value.length === 0) {
      spawnBoss();
    }

    // 更新子弹
    updateBullets();

    // 更新敌人
    updateEnemies();

    // 更新BOSS
    if (currentBoss.value) {
      updateBoss(deltaTime);
    }

    // 更新爆炸效果
    updateExplosions();

    // 更新道具
    updatePowerUps();

    // 碰撞检测
    checkCollisions();

    // 继续游戏循环
    if (gameState.value === 'playing') {
      gameLoop.value = requestAnimationFrame(gameUpdate);
    }
  }

  // 更新玩家状态
  function updatePlayer() {
    // 处理无敌状态
    if (playerInvincible.value) {
      playerInvincibleTimer.value++;
      if (playerInvincibleTimer.value > 180) { // 无敌状态持续180帧
        playerInvincible.value = false;
        playerInvincibleTimer.value = 0;
      }
    }
  }

  // 处理射击逻辑
  function handleShooting() {
    fireTimer.value++;
    if (fireTimer.value >= fireRate.value) {
      fireTimer.value = 0;
      firePlayerBullet();
    }

    // 敌人射击
    if (enemies.value.length > 0 && Math.random() < 0.01) {
      const randomEnemy = enemies.value[Math.floor(Math.random() * enemies.value.length)];
      fireEnemyBullet(randomEnemy);
    }

    // BOSS射击
    if (currentBoss.value && Math.random() < 0.02) {
      fireBossBullets(currentBoss.value);
    }
  }

  // 玩家发射子弹
  function firePlayerBullet() {
    const bulletX = playerX.value + playerSize / 2 - bulletSize / 2;
    const bulletY = playerY.value - bulletSize;

    playerBullets.value.push({
      x: bulletX,
      y: bulletY,
      size: bulletSize
    });
  }

  // 敌人发射子弹
  function fireEnemyBullet(enemy) {
    const bulletX = enemy.x + enemy.size / 2 - bulletSize / 2;
    const bulletY = enemy.y + enemy.size;

    enemyBullets.value.push({
      x: bulletX,
      y: bulletY,
      size: bulletSize
    });
  }

  // BOSS发射子弹
  function fireBossBullets(boss) {
    switch (boss.attack) {
      case 'single':
        // 单发射击
        enemyBullets.value.push({
          x: boss.x + boss.size / 2 - bulletSize / 2,
          y: boss.y + boss.size,
          size: bulletSize
        });
        break;
      case 'triple':
        // 三发射击
        for (let i = -1; i <= 1; i++) {
          enemyBullets.value.push({
            x: boss.x + boss.size / 2 - bulletSize / 2,
            y: boss.y + boss.size,
            size: bulletSize,
            dx: i * 1.5
          });
        }
        break;
      case 'spread':
        // 扇形射击
        const angleCount = 7;
        const angleStep = Math.PI / 6;
        for (let i = 0; i < angleCount; i++) {
          const angle = (i - 3) * angleStep;
          enemyBullets.value.push({
            x: boss.x + boss.size / 2 - bulletSize / 2,
            y: boss.y + boss.size,
            size: bulletSize,
            dx: Math.sin(angle) * 3,
            dy: Math.cos(angle) * 3
          });
        }
        break;
      case 'homing':
        // 跟踪弹
        const playerCenterX = playerX.value + playerSize / 2;
        const playerCenterY = playerY.value + playerSize / 2;
        const bossCenterX = boss.x + boss.size / 2;
        const bossCenterY = boss.y + boss.size / 2;

        const dx = playerCenterX - bossCenterX;
        const dy = playerCenterY - bossCenterY;
        const distance = Math.sqrt(dx * dx + dy * dy);

        enemyBullets.value.push({
          x: bossCenterX - bulletSize / 2,
          y: bossCenterY - bulletSize / 2,
          size: bulletSize,
          dx: (dx / distance) * 2.5,
          dy: (dy / distance) * 2.5,
          homing: true
        });
        break;
      case 'mixed':
        // 混合攻击 - 随机使用前面的攻击方式
        const attacks = ['single', 'triple', 'spread', 'homing'];
        const randomAttack = attacks[Math.floor(Math.random() * attacks.length)];

        // 递归调用不同的攻击方式
        const tempBoss = {
          ...boss,
          attack: randomAttack
        };
        fireBossBullets(tempBoss);

        // 额外增加一颗大子弹
        if (Math.random() < 0.5) {
          enemyBullets.value.push({
            x: boss.x + boss.size / 2 - 10,
            y: boss.y + boss.size,
            size: 20,
            dx: (Math.random() - 0.5) * 2,
            dy: 4,
            heavy: true
          });
        }
        break;
    }
  }

  // 生成敌人
  function spawnEnemies(deltaTime) {
    // 有BOSS时不生成普通敌人
    if (currentBoss.value) return;

    enemySpawnTimer.value += deltaTime;
    // 随关卡提升，生成速度加快
    const spawnInterval = Math.max(1500 - (currentLevel.value - 1) * 200, 500);

    if (enemySpawnTimer.value > spawnInterval && enemies.value.length < 8) {
      enemySpawnTimer.value = 0;

      // 随机敌人类型
      const enemyType = enemyTypes[Math.floor(Math.random() * enemyTypes.length)];
      const enemySize = 40 + enemyType * 5;

      // 随机x位置，确保在屏幕内
      const x = Math.random() * (windowWidth.value - enemySize);
      const y = -enemySize;

      // 根据类型设置属性
      let health, scoreValue, speed;
      switch (enemyType) {
        case 1:
          health = 1;
          scoreValue = 10;
          speed = 3;
          break;
        case 2:
          health = 2;
          scoreValue = 20;
          speed = 2.5;
          break;
        case 3:
          health = 3;
          scoreValue = 30;
          speed = 2;
          break;
      }

      // 随关卡提升增强敌人
      const levelMultiplier = 1 + (currentLevel.value - 1) * 0.2;
      health = Math.floor(health * levelMultiplier);
      scoreValue = Math.floor(scoreValue * levelMultiplier);

      enemies.value.push({
        x,
        y,
        size: enemySize,
        type: enemyType,
        health,
        maxHealth: health,
        scoreValue,
        speed
      });
    }
  }

  // 生成BOSS
  function spawnBoss() {
    if (currentLevel.value > maxLevels) return;

    const bossConfig = bossConfigurations[currentLevel.value - 1];
    const bossSize = 120 + (bossConfig.type - 1) * 15;

    // 计算BOSS属性（随关卡提升）
    const levelMultiplier = 1 + (currentLevel.value - 1) * 0.3;
    const health = Math.floor(bossConfig.health * levelMultiplier);
    const scoreValue = Math.floor(bossConfig.score * levelMultiplier);

    currentBoss.value = {
      x: windowWidth.value / 2 - bossSize / 2,
      y: 50,
      size: bossSize,
      type: bossConfig.type,
      health,
      maxHealth: health,
      scoreValue,
      speed: bossConfig.speed,
      pattern: bossConfig.pattern,
      attack: bossConfig.attack,
      rotation: 0,
      moveTimer: 0,
      directionX: 1,
      phase: 0
    };

    bossSpawned.value = true;
  }

  // 更新子弹位置
  function updateBullets() {
    // 更新玩家子弹
    for (let i = playerBullets.value.length - 1; i >= 0; i--) {
      const bullet = playerBullets.value[i];
      bullet.y -= bulletSpeed;

      // 移除出界子弹
      if (bullet.y < -bullet.size) {
        playerBullets.value.splice(i, 1);
      }
    }

    // 更新敌人子弹
    for (let i = enemyBullets.value.length - 1; i >= 0; i--) {
      const bullet = enemyBullets.value[i];

      if (bullet.homing) {
        // 跟踪弹移动
        bullet.x += bullet.dx;
        bullet.y += bullet.dy;
      } else if (bullet.dx !== undefined) {
        // 有横向速度的子弹
        bullet.x += bullet.dx;
        bullet.y += bullet.heavy ? bullet.dy : bulletSpeed;
      } else {
        // 普通子弹
        bullet.y += bulletSpeed;
      }

      // 移除出界子弹
      if (bullet.y > windowHeight.value ||
        bullet.x < -bullet.size ||
        bullet.x > windowWidth.value) {
        enemyBullets.value.splice(i, 1);
      }
    }
  }

  // 更新敌人位置
  function updateEnemies() {
    for (let i = enemies.value.length - 1; i >= 0; i--) {
      const enemy = enemies.value[i];

      // 移动敌人（简单AI）
      enemy.y += enemy.speed;

      // 随机横向移动
      if (Math.random() < 0.02) {
        enemy.x += (Math.random() - 0.5) * 20;
      }

      // 限制在屏幕内
      if (enemy.x < 0) enemy.x = 0;
      if (enemy.x > windowWidth.value - enemy.size) {
        enemy.x = windowWidth.value - enemy.size;
      }

      // 移除出界敌人
      if (enemy.y > windowHeight.value) {
        enemies.value.splice(i, 1);
        // 敌人逃脱，扣除分数
        score.value = Math.max(0, score.value - 10);
      }
    }
  }

  // 更新BOSS
  function updateBoss(deltaTime) {
    const boss = currentBoss.value;
    boss.moveTimer += deltaTime;
    boss.rotation = (boss.rotation + 0.5) % 360;

    // 根据不同模式移动
    switch (boss.pattern) {
      case 'horizontal':
        // 左右移动
        boss.x += boss.speed * boss.directionX;
        if (boss.x <= 0 || boss.x >= windowWidth.value - boss.size) {
          boss.directionX *= -1;
        }
        break;
      case 'zigzag':
        // 之字形移动
        boss.x += boss.speed * boss.directionX;
        boss.y += Math.sin(boss.moveTimer / 300) * 0.8;

        if (boss.x <= 0 || boss.x >= windowWidth.value - boss.size) {
          boss.directionX *= -1;
        }
        break;
      case 'circular':
        // 圆形移动
        const centerX = windowWidth.value / 2 - boss.size / 2;
        const centerY = 150;
        const radius = 100;
        const angle = boss.moveTimer / 1000;

        boss.x = centerX + Math.cos(angle) * radius;
        boss.y = centerY + Math.sin(angle) * radius;
        break;
      case 'chase':
        // 追逐玩家
        const targetX = playerX.value + playerSize / 2 - boss.size / 2;

        if (boss.x < targetX - 20) {
          boss.x += boss.speed;
        } else if (boss.x > targetX + 20) {
          boss.x -= boss.speed;
        }

        // 限制Y轴位置
        if (boss.y < 50) boss.y = 50;
        if (boss.y > windowHeight.value / 3) boss.y = windowHeight.value / 3;
        break;
      case 'phase':
        // 阶段式移动
        boss.phase = Math.floor(boss.moveTimer / 5000) % 3; // 每5秒切换一次阶段

        switch (boss.phase) {
          case 0:
            // 阶段1: 左右移动
            boss.x += boss.speed * boss.directionX;
            if (boss.x <= 0 || boss.x >= windowWidth.value - boss.size) {
              boss.directionX *= -1;
            }
            break;
          case 1:
            // 阶段2: 圆形移动
            const centerX = windowWidth.value / 2 - boss.size / 2;
            const centerY = 200;
            const radius = 150;
            const angle = (boss.moveTimer % 5000) / 1000;

            boss.x = centerX + Math.cos(angle) * radius;
            boss.y = centerY + Math.sin(angle) * radius;
            break;
          case 2:
            // 阶段3: 追逐玩家
            const targetX = playerX.value + playerSize / 2 - boss.size / 2;
            if (boss.x < targetX) {
              boss.x += boss.speed * 1.2;
            } else {
              boss.x -= boss.speed * 1.2;
            }

            // 上下移动
            if (boss.y < 50 || boss.y > windowHeight.value / 3) {
              boss.directionX *= -1;
            }
            boss.y += boss.directionX * 0.5;
            break;
        }
        break;
    }
  }

  // 更新爆炸效果
  function updateExplosions() {
    for (let i = explosions.value.length - 1; i >= 0; i--) {
      const explosion = explosions.value[i];
      explosion.life--;
      explosion.opacity = explosion.life / 20;
      explosion.scale = 1 + (20 - explosion.life) / 20;

      if (explosion.life <= 0) {
        explosions.value.splice(i, 1);
      }
    }
  }

  // 更新道具
  function updatePowerUps() {
    for (let i = powerUps.value.length - 1; i >= 0; i--) {
      const powerUp = powerUps.value[i];
      powerUp.y += 2;

      // 移除出界道具
      if (powerUp.y > windowHeight.value) {
        powerUps.value.splice(i, 1);
        continue;
      }

      // 检查玩家是否拾取
      if (checkCollision({
          x: playerX.value,
          y: playerY.value,
          size: playerSize
        }, {
          x: powerUp.x,
          y: powerUp.y,
          size: 30
        })) {
        applyPowerUp(powerUp.type);
        powerUps.value.splice(i, 1);
      }
    }
  }

  // 应用道具效果
  function applyPowerUp(type) {
    switch (type) {
      case 'health':
        if (playerLives.value < 5) {
          playerLives.value++;
          showMessage("+1 生命");
        }
        break;
      case 'speed':
        if (playerSpeed.value < 8) {
          playerSpeed.value += 0.5;
          showMessage("速度提升");
        }
        break;
      case 'fire':
        if (fireRate.value > 5) {
          fireRate.value -= 2;
          showMessage("射速提升");
        }
        break;
      case 'shield':
        playerInvincible.value = true;
        playerInvincibleTimer.value = 0;
        showMessage("获得护盾");
        break;
    }
  }

  // 显示临时消息
  function showMessage(text) {
    // 可以在这里实现消息显示逻辑
    console.log(text);
  }

  // 碰撞检测
  function checkCollisions() {
    // 玩家子弹 vs 敌人
    for (let i = playerBullets.value.length - 1; i >= 0; i--) {
      const bullet = playerBullets.value[i];

      // 检测与普通敌人的碰撞
      for (let j = enemies.value.length - 1; j >= 0; j--) {
        const enemy = enemies.value[j];

        if (checkCollision(bullet, enemy)) {
          // 移除子弹
          playerBullets.value.splice(i, 1);

          // 敌人受伤
          enemy.health--;

          // 敌人被消灭
          if (enemy.health <= 0) {
            // 爆炸效果
            addExplosion(enemy.x + enemy.size / 2, enemy.y + enemy.size / 2, enemy.size / 2);

            // 加分
            score.value += enemy.scoreValue;

            // 随机掉落道具
            if (Math.random() < 0.15) {
              const powerUp = powerUpTypes[Math.floor(Math.random() * powerUpTypes.length)];
              powerUps.value.push({
                x: enemy.x + enemy.size / 2 - 15,
                y: enemy.y + enemy.size / 2 - 15,
                ...powerUp
              });
            }

            // 移除敌人
            enemies.value.splice(j, 1);
          }

          break;
        }
      }

      // 检测与BOSS的碰撞
      if (currentBoss.value && checkCollision(bullet, currentBoss.value)) {
        // 移除子弹
        playerBullets.value.splice(i, 1);

        // BOSS受伤
        currentBoss.value.health--;

        // BOSS被消灭
        if (currentBoss.value.health <= 0) {
          // 爆炸效果
          addExplosion(
            currentBoss.value.x + currentBoss.value.size / 2,
            currentBoss.value.y + currentBoss.value.size / 2,
            currentBoss.value.size / 2
          );

          // 加分
          score.value += currentBoss.value.scoreValue;

          // 检查是否通关
          if (currentLevel.value >= maxLevels) {
            gameVictory();
          } else {
            // 关卡完成
            levelComplete();
          }
        }
      }
    }

    // 敌人子弹 vs 玩家
    if (!playerInvincible.value) {
      for (let i = enemyBullets.value.length - 1; i >= 0; i--) {
        const bullet = enemyBullets.value[i];

        if (checkCollision(bullet, {
            x: playerX.value,
            y: playerY.value,
            size: playerSize
          })) {
          // 移除子弹
          enemyBullets.value.splice(i, 1);

          // 玩家受伤
          loseLife();
          break;
        }
      }
    }

    // 玩家 vs 敌人碰撞
    if (!playerInvincible.value) {
      for (let i = enemies.value.length - 1; i >= 0; i--) {
        const enemy = enemies.value[i];

        if (checkCollision(enemy, {
            x: playerX.value,
            y: playerY.value,
            size: playerSize
          })) {
          // 爆炸效果
          addExplosion(enemy.x + enemy.size / 2, enemy.y + enemy.size / 2, enemy.size / 2);

          // 移除敌人
          enemies.value.splice(i, 1);

          // 玩家受伤
          loseLife();
          break;
        }
      }
    }

    // 玩家 vs BOSS碰撞
    if (currentBoss.value && !playerInvincible.value) {
      if (checkCollision(currentBoss.value, {
          x: playerX.value,
          y: playerY.value,
          size: playerSize
        })) {
        // 玩家受伤
        loseLife();
      }
    }
  }

  // 碰撞检测辅助函数
  function checkCollision(obj1, obj2) {
    return obj1.x < obj2.x + obj2.size &&
      obj1.x + obj1.size > obj2.x &&
      obj1.y < obj2.y + obj2.size &&
      obj1.y + obj1.size > obj2.y;
  }

  // 添加爆炸效果
  function addExplosion(x, y, size) {
    explosions.value.push({
      x: x - size,
      y: y - size,
      size: size * 2,
      life: 20,
      opacity: 1,
      scale: 1
    });
  }

  // 玩家失去生命
  function loseLife() {
    playerLives.value--;
    playerInvincible.value = true;
    playerInvincibleTimer.value = 0;

    // 爆炸效果
    addExplosion(playerX.value + playerSize / 2, playerY.value + playerSize / 2, playerSize / 2);

    // 游戏结束
    if (playerLives.value <= 0) {
      gameOver();
    } else {
      // 重置位置
      resetPlayerPosition();
    }
  }

  // 关卡完成
  function levelComplete() {
    // 清除BOSS
    currentBoss.value = null;
    bossSpawned.value = false;

    // 计算奖励
    levelReward.value = currentLevel.value * 200;
    score.value += levelReward.value;

    // 显示关卡完成界面
    gameState.value = 'levelComplete';
    cancelAnimationFrame(gameLoop.value);
  }

  // 游戏胜利（通关）
  function gameVictory() {
    currentBoss.value = null;
    bossSpawned.value = false;

    // 显示胜利界面
    gameState.value = 'victory';
    cancelAnimationFrame(gameLoop.value);
  }

  // 游戏结束
  function gameOver() {
    gameState.value = 'gameOver';
    cancelAnimationFrame(gameLoop.value);
  }

  // 暂停游戏
  function pauseGame() {
    gameState.value = 'paused';
    cancelAnimationFrame(gameLoop.value);
  }

  // 恢复游戏
  function resumeGame() {
    gameState.value = 'playing';
    startGameLoop();
  }

  // 重新开始
  function restartGame() {
    cancelAnimationFrame(gameLoop.value);
    startGame();
  }

  // 退出游戏
  function quitGame() {
    cancelAnimationFrame(gameLoop.value);
    gameState.value = 'start';
  }

  // 进入下一关
  function nextLevel() {
    currentLevel.value++;
    gameState.value = 'playing';
    startGameLoop();
  }

  // 触摸事件处理
  function handleTouchStart(e) {
    isTouching.value = true;
  }

  function handleTouchMove(e) {
    if (!isTouching.value) return;

    // 获取触摸位置
    const touch = e.touches[0];
    let newX = touch.clientX - playerSize / 2;
    let newY = touch.clientY - playerSize / 2;

    // 限制在屏幕内
    if (newX < 0) newX = 0;
    if (newX > windowWidth.value - playerSize) {
      newX = windowWidth.value - playerSize;
    }
    if (newY < 0) newY = 0;
    if (newY > windowHeight.value - playerSize) {
      newY = windowHeight.value - playerSize;
    }

    // 更新玩家位置
    playerX.value = newX;
    playerY.value = newY;
  }

  function handleTouchEnd() {
    isTouching.value = false;
  }

  // 组件生命周期
  onMounted(() => {
    updateWindowSize();
    uni.onWindowResize(updateWindowSize);
  });

  onUnmounted(() => {
    cancelAnimationFrame(gameLoop.value);
    uni.offWindowResize(updateWindowSize);
  });
</script>

<style scoped>
  .game-container {
    width: 100%;
    height: 100vh;
    background-color: #000;
    overflow: hidden;
    position: relative;
  }

  /* 开始界面 */
  .start-screen {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: linear-gradient(135deg, #050a30 0%, #1a2a6c 100%);
    color: #fff;
    padding: 30rpx;
  }

  .game-title {
    font-size: 80rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    text-shadow: 0 0 15rpx rgba(255, 255, 255, 0.7);
    animation: pulse 2s infinite;
  }

  .game-subtitle {
    font-size: 36rpx;
    color: #ccc;
    margin-bottom: 80rpx;
  }

  .start-button {
    width: 320rpx;
    height: 90rpx;
    background-color: #ff5722;
    color: white;
    border: none;
    border-radius: 45rpx;
    font-size: 38rpx;
    font-weight: bold;
    margin-bottom: 100rpx;
    box-shadow: 0 5rpx 20rpx rgba(255, 87, 34, 0.6);
    transition: all 0.3s ease;
  }

  .start-button:active {
    transform: scale(0.95);
    box-shadow: 0 2rpx 10rpx rgba(255, 87, 34, 0.6);
  }

  .instructions {
    display: flex;
    flex-direction: column;
    gap: 30rpx;
    width: 80%;
  }

  .instruction {
    display: flex;
    align-items: center;
    gap: 15rpx;
    font-size: 30rpx;
    background-color: rgba(255, 255, 255, 0.1);
    padding: 20rpx;
    border-radius: 15rpx;
  }

  .icon {
    font-size: 36rpx;
  }

  /* 游戏界面 */
  .game-screen {
    width: 100%;
    height: 100%;
    position: relative;
    background-image:
      radial-gradient(circle at 2px 2px, rgba(255, 255, 255, 0.1) 1px, transparent 0),
      linear-gradient(to bottom, #0a0e2c 0%, #141a46 100%);
    background-size: 30px 30px;
  }

  /* 状态栏 */
  .status-bar {
    display: flex;
    justify-content: space-between;
    padding: 15rpx 20rpx;
    background-color: rgba(0, 0, 0, 0.6);
    color: #fff;
    font-size: 26rpx;
    z-index: 10;
    position: relative;
  }

  .status-item {
    background-color: rgba(255, 255, 255, 0.1);
    padding: 5rpx 15rpx;
    border-radius: 15rpx;
  }

  /* 游戏区域 */
  .game-area {
    width: 100%;
    height: calc(100% - 60rpx);
    position: relative;
    overflow: hidden;
  }

  /* 玩家飞机 */
  .player {
    position: absolute;
    width: 60rpx;
    height: 60rpx;
    z-index: 5;
    transition: transform 0.1s ease;
  }

  .player-img {
    width: 100%;
    height: 100%;
  }

  .thruster {
    position: absolute;
    bottom: -10rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 20rpx;
    height: 30rpx;
    background: linear-gradient(to bottom, #ff9800, #ffeb3b);
    border-radius: 50%;
    filter: blur(2rpx);
    animation: thruster 0.3s infinite alternate;
  }

  /* 敌人飞机 */
  .enemy {
    position: absolute;
    z-index: 4;
  }

  .enemy.type1 {
    width: 45rpx;
    height: 45rpx;
  }

  .enemy.type2 {
    width: 55rpx;
    height: 55rpx;
  }

  .enemy.type3 {
    width: 65rpx;
    height: 65rpx;
  }

  .enemy-img {
    width: 100%;
    height: 100%;
  }

  .enemy-health-bar {
    position: absolute;
    top: -10rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 80%;
    height: 8rpx;
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 4rpx;
  }

  .enemy-health {
    height: 100%;
    background-color: #ff4444;
    transition: width 0.2s ease;
  }

  /* BOSS飞机 */
  .boss {
    position: absolute;
    z-index: 4;
    transition: all 0.2s ease;
  }

  .boss-img {
    width: 100%;
    height: 100%;
    filter: drop-shadow(0 0 15rpx rgba(255, 68, 68, 0.6));
  }

  .boss-health-bar {
    position: absolute;
    bottom: -15rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 90%;
    height: 12rpx;
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 6rpx;
  }

  .boss-health {
    height: 100%;
    background: linear-gradient(to right, #ff4444, #ff9800);
    transition: width 0.2s ease;
  }

  /* 子弹 */
  .bullet {
    position: absolute;
    border-radius: 50%;
    z-index: 3;
  }

  .player-bullet {
    width: 8rpx;
    height: 16rpx;
    background-color: #00ffff;
    box-shadow: 0 0 10rpx #00ffff;
  }

  .enemy-bullet {
    width: 8rpx;
    height: 16rpx;
    background-color: #ff4444;
    box-shadow: 0 0 10rpx #ff4444;
  }

  .enemy-bullet.heavy {
    width: 20rpx;
    height: 20rpx;
    background-color: #ff9800;
    box-shadow: 0 0 15rpx #ff9800;
  }

  /* 爆炸效果 */
  .explosion {
    position: absolute;
    background: radial-gradient(circle, #ffeb3b, #ff9800, #f44336);
    border-radius: 50%;
    z-index: 6;
    opacity: 0.8;
    filter: blur(2rpx);
  }

  /* 道具 */
  .power-up {
    position: absolute;
    width: 30rpx;
    height: 30rpx;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 20rpx;
    z-index: 4;
    animation: float 1s infinite alternate;
  }

  .power-up.health {
    background-color: rgba(255, 68, 68, 0.8);
  }

  .power-up.speed {
    background-color: rgba(255, 235, 59, 0.8);
  }

  .power-up.fire {
    background-color: rgba(255, 152, 0, 0.8);
  }

  .power-up.shield {
    background-color: rgba(33, 150, 243, 0.8);
  }

  /* 暂停按钮 */
  .pause-btn {
    position: absolute;
    top: 70rpx;
    right: 20rpx;
    width: 50rpx;
    height: 50rpx;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.2);
    color: white;
    border: none;
    font-size: 24rpx;
    z-index: 10;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  /* 弹窗通用样式 */
  .popup-screen {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.85);
    position: absolute;
    top: 0;
    left: 0;
    z-index: 100;
  }

  .popup {
    width: 80%;
    max-width: 500rpx;
    background-color: #1a1a2e;
    border-radius: 30rpx;
    padding: 50rpx 30rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-shadow: 0 10rpx 50rpx rgba(0, 0, 0, 0.5);
  }

  .popup.victory {
    background: linear-gradient(135deg, #1a1a2e 0%, #2541b2 100%);
  }

  .popup-title {
    font-size: 50rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 40rpx;
    text-align: center;
  }

  .popup-title:first-child {
    color: #ff5722;
  }

  .victory .popup-title {
    color: #4caf50;
    text-shadow: 0 0 15rpx rgba(76, 175, 80, 0.7);
  }

  .final-score {
    font-size: 36rpx;
    color: #ffeb3b;
    margin-bottom: 20rpx;
    font-weight: bold;
  }

  .final-level,
  .level-reward,
  .victory-message {
    font-size: 32rpx;
    color: #ccc;
    margin-bottom: 40rpx;
    text-align: center;
  }

  .victory-message {
    color: #bbdefb;
    margin-bottom: 60rpx;
  }

  .popup-btn {
    width: 80%;
    height: 80rpx;
    margin-bottom: 20rpx;
    border-radius: 40rpx;
    font-size: 32rpx;
    border: none;
    color: white;
    font-weight: bold;
    transition: all 0.2s ease;
  }

  .popup-btn:active {
    transform: scale(0.95);
  }

  .resume {
    background-color: #4caf50;
  }

  .restart {
    background-color: #2196f3;
  }

  .quit {
    background-color: #f44336;
  }

  .next {
    background-color: #ff9800;
    margin-top: 20rpx;
  }

  /* 动画 */
  @keyframes pulse {
    0% {
      transform: scale(1);
    }

    50% {
      transform: scale(1.05);
    }

    100% {
      transform: scale(1);
    }
  }

  @keyframes thruster {
    0% {
      height: 20rpx;
      opacity: 0.7;
    }

    100% {
      height: 30rpx;
      opacity: 1;
    }
  }

  @keyframes float {
    0% {
      transform: translateY(0);
    }

    100% {
      transform: translateY(-10rpx);
    }
  }
</style>